All files / src/services favorites.ts

36.66% Statements 22/60
56.25% Branches 9/16
28.57% Functions 4/14
37.73% Lines 20/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 1761x                                                                   1x           2x 2x 2x   1x 1x                                                 1x 1x     1x                                                                                                                                         3x       3x 3x 1x     2x 1x 1x         1x                           1x 3x  
import apiService from './api';
import { ApiResult } from '@/types';
 
export type ContentType = 'movie' | 'series' | 'channel';
 
export interface FavoritesData {
  movies: string[];
  series: string[];
  channels: string[];
  music_tracks: string[];
  music_albums: string[];
  music_artists: string[];
}
 
interface BackendResponse<T> {
  success: boolean;
  data?: T | null;
  error?: string | null;
}
 
interface FavoriteRecord {
  id: number;
  user_id: number;
  content_type: ContentType;
  content_id: string;
  created_at: string;
}
 
export interface AddFavoriteRequest {
  content_type: ContentType;
  content_id: string;
}
 
class FavoritesService {
  private baseUrl = '/api/user/favorites';
 
  /**
   * Get all favorites for the current user
   */
  async getFavorites(): Promise<FavoritesData> {
    try {
      const response = await apiService.get<BackendResponse<FavoritesData>>(this.baseUrl);
      return this.unwrap(response, 'Error fetching favorites', () => this.createEmptyFavorites());
    } catch (error) {
      console.error('Error fetching favorites:', error);
      throw error;
    }
  }
 
  /**
   * Add a favorite
   */
  async addFavorite(contentType: ContentType, contentId: string): Promise<boolean> {
    try {
      const request: AddFavoriteRequest = {
        content_type: contentType,
        content_id: contentId};
      const response = await apiService.post<BackendResponse<FavoriteRecord>>(this.baseUrl, request);
      this.unwrap(response, 'Error adding favorite');
      return true;
    } catch (error) {
      console.error('Error adding favorite:', error);
      throw error;
    }
  }
 
  /**
   * Remove a favorite
   */
  async removeFavorite(contentType: ContentType, contentId: string): Promise<boolean> {
    try {
      const response = await apiService.delete<BackendResponse<boolean>>(
        `${this.baseUrl}/${contentType}/${contentId}`
      );
      return this.unwrap(response, 'Error removing favorite', () => false);
    } catch (error) {
      console.error('Error removing favorite:', error);
      throw error;
    }
  }
 
  /**
   * Check if content is favorited
   */
  async isFavorite(contentType: ContentType, contentId: string): Promise<boolean> {
    try {
      const response = await apiService.get<BackendResponse<boolean>>(
        `${this.baseUrl}/check/${contentType}/${contentId}`
      );
      return this.unwrap(response, 'Error checking favorite', () => false);
    } catch (error) {
      console.error('Error checking favorite:', error);
      return false;
    }
  }
 
  /**
   * Get favorites by type
   */
  async getFavoritesByType(contentType: ContentType): Promise<string[]> {
    try {
      const response = await apiService.get<BackendResponse<string[]>>(
        `${this.baseUrl}/type/${contentType}`
      );
      return this.unwrap(response, 'Error fetching favorites by type', () => []);
    } catch (error) {
      console.error('Error fetching favorites by type:', error);
      return [];
    }
  }
 
  /**
   * Get favorites statistics
   */
  async getFavoritesStats(): Promise<Record<string, number>> {
    try {
      const response = await apiService.get<BackendResponse<Record<string, number>>>(`${this.baseUrl}/stats`);
      return this.unwrap(response, 'Error fetching favorites stats', () => ({}));
    } catch (error) {
      console.error('Error fetching favorites stats:', error);
      return {};
    }
  }
 
  /**
   * Toggle favorite status
   */
  async toggleFavorite(contentType: ContentType, contentId: string): Promise<boolean> {
    const isFav = await this.isFavorite(contentType, contentId);
    if (isFav) {
      await this.removeFavorite(contentType, contentId);
      return false;
    } else {
      await this.addFavorite(contentType, contentId);
      return true;
    }
  }
 
  private unwrap<T>(
    response: ApiResult<BackendResponse<T>>,
    errorMessage: string,
    fallback?: () => T
  ): T {
    Iif (!response.success) {
      throw new Error(response.error?.details ?? errorMessage);
    }
 
    const payload = response.data;
    if (!payload?.success) {
      throw new Error(payload?.error ?? errorMessage);
    }
 
    if (payload.data === undefined || payload.data === null) {
      Eif (fallback) {
        return fallback();
      }
      throw new Error(errorMessage);
    }
 
    return payload.data;
  }
 
  private createEmptyFavorites(): FavoritesData {
    return {
      movies: [],
      series: [],
      channels: [],
      music_tracks: [],
      music_albums: [],
      music_artists: []};
  }
}
 
export const favoritesService = new FavoritesService();
export default favoritesService;